from flask import Blueprint, request, jsonify, g
from app.err_no import errno_no
import json
from loguru import logger
from app.db.mongoClient import MongoError
from app.db import dbUserRole
import traceback

blueprint = Blueprint('user_role', __name__, url_prefix='/api/user')


@blueprint.route('/v1/role_query', methods=['POST'])
def role_query():
    '''
    查询所有角色及权限
    '''
    try:
        data = dbUserRole.queryAllRole()
        return jsonify(errno_no.OK.data({'roleList': data}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/role_create', methods=['POST'])
def role_create():
    '''
    创建角色及其权限
    '''
    try:
        j_data = json.loads(request.data)
        roleName = j_data.get('roleName')
        roleDesc = j_data.get('roleDesc')
        rolePower = j_data.get('rolePower')
        if roleName is None or len(roleName) <= 0 or roleName.isalnum() is False\
            or roleDesc is None \
            or rolePower is None or len(rolePower) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        roleId = dbUserRole.createRole(roleName, rolePower, roleDesc, g.userId)
        if roleId is None:
            return jsonify(errno_no.ErrServerDocumentExist.data(None))

        return jsonify(errno_no.OK.data({'roleId': roleId}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/role_edit', methods=['POST'])
def role_edit():
    '''
    编辑角色
    '''
    try:
        j_data = json.loads(request.data)
        roleId = j_data.get('roleId')
        roleName = j_data.get('roleName')
        roleDesc = j_data.get('roleDesc')
        rolePower = j_data.get('rolePower')
        if roleId is None or len(roleId) <= 0 \
            or roleName is None or len(roleName) <= 0 or roleName.isalnum() is False\
            or roleDesc is None \
            or rolePower is None or len(rolePower) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))
        
        if roleName is None or roleId is None or rolePower is None:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbUserRole.editRole(roleId, roleName, rolePower, roleDesc)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))
        #如果要编辑超级管理员则不让操作
        if res is False:
            return jsonify(errno_no.ErrServerPermissionDenied.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/role_del', methods=['POST'])
def role_del():
    '''
    删除角色
    '''
    try:
        j_data = json.loads(request.data)
        roleId = j_data.get('roleId')
        if roleId is None or len(roleId) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbUserRole.delRole(roleId)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        #如果要删除超级管理员则不让操作
        if res is False:
            return jsonify(errno_no.ErrServerPermissionDenied.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
